"""
# coding     : utf-8 
# Time       : 2025/6/16 10:15
# Author     : chenxianb
# version    : python 3.8.2
# Description: 获取表情包
"""
import os.path
import time

import requests
from bs4 import BeautifulSoup


class Emoticon():

    def get_html_text(self, url):

        header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0",
                  "Refer": "https://fabiaoqing.com/",
                  "Host": "ep1.adtrafficquality.google"}

        try:
            r = requests.get(url, headers=header)
            r.raise_for_status()
            r.encoding = r.apparent_encoding
            return r.text
        except:
            return ""

    def get_emoji_url(self, html):
        """获取每个页面中表情包对应的链接"""
        url_lst = []
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all("div", "searchbqppdiv tagbqppdiv"):
            url = item.a["href"]
            name = item.a.img["data-original"].split("/")[-1]

            url_lst.append([name,url])

        return url_lst

    def save_emoji(self, path, lst, host):
        """保存到指定的目录中"""

        if not os.path.exists(path):
            os.mkdir(path)

        for item in lst:
            emoji_url = f"{host}{item[-1]}"
            emoji_name = item[0]
            print(emoji_url)
            print(emoji_name)

            time.sleep(1)

            # 使用代理访问
            # proxy={"http":"122.114.31.177:808",
            #        "https":"122.114.31.177:808"}
            # res = requests.get(emoji_url,proxies=proxy)

            res = requests.get(emoji_url)
            emoji_path = f"{path}/{emoji_name}"
            with open(emoji_path, "wb") as f:
                f.write(res.content)
                print(f"{emoji_name}  下载成功")
                time.sleep(1)



if __name__ == '__main__':
    url = "https://fabiaoqing.com/search/bqb/keyword/%E6%89%93%E5%B7%A5%E4%BA%BA/type/bq.html"
    host = "https://fabiaoqing.com"
    path = "./emoji/"
    em = Emoticon()
    html = em.get_html_text(url)
    info = em.get_emoji_url(html)
    em.save_emoji(path=path, lst=info, host=host)
